//图片转base64钩子函数
import { onMounted } from "vue";

type Options = {
  el: string;
};
export function useImgToBase64(options: Options): Promise<{ baseUrl: string }> {
  return new Promise(resolve => {
    const base64 = (el: HTMLImageElement) => {
      const cvs = document.createElement("canvas");
      const ctx = cvs.getContext("2d");
      // 设置canvas的宽高为图片的宽高，确保图片完整显示
      cvs.width = el.width;
      cvs.height = el.height;
      ctx?.drawImage(el, 0, 0, cvs.width, cvs.height);
      // type：图片格式，默认为 image/png,可以是其他image/jpeg等
      return cvs.toDataURL("image/png");
    };
    onMounted(() => {
      const img = document.querySelector(options.el) as HTMLImageElement;
      img.onload = () => {
        resolve({
          baseUrl: base64(img),
        });
      };
    });
  });
}
